// 写cookies
function setCookie(name: string, value: string, time: any) {
  const strsec: any = getsec(time);
  const exp = new Date();
  exp.setTime(exp.getTime() + strsec * 1);
  document.cookie =
    name + '=' + escape(value) + ';expires=' + exp.toUTCString();
}

// cookie操作辅助函数
function getsec(str: any): number {
  const str1 = str.substring(1, str.length) * 1;
  const str2 = str.substring(0, 1);
  if (str2 === 's') {
    return str1 * 1000;
  } else if (str2 === 'm') {
    return str1 * 60 * 1000;
  } else if (str2 === 'h') {
    return str1 * 60 * 60 * 1000;
  } else if (str2 === 'd') {
    return str1 * 24 * 60 * 60 * 1000;
  } else {
    // 如果随便填 默认 30分钟
    return 30  * 60 * 1000;
  }
}
// 读取cookies
function getCookie(name) {
  let arr;
  const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
  // tslint:disable-next-line: no-conditional-assignment
  if ((arr = document.cookie.match(reg))) return arr[2];
  else return null;
}

// 删除cookies
function delCookie(name) {
  const exp = new Date();
  exp.setTime(exp.getTime() - 1);
  const cval = getCookie(name);
  if (cval != null) {
    document.cookie = name + '=' + cval + ';expires=' + exp.toUTCString();
  }
}

export default { setCookie, getCookie, delCookie };
